import { transferToOutputCondition, openWindow } from '@/utils'
import store from '@/store'
import config from '@/config'

export default {
  data () {
    return {
      service: null,
      loading: false,
      resData: {},
      list: [],
      pageData: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 1,
        totalSize: 1
      },
      pageCondition: {
        pageSize: 10,
        pageNo: 1
      },
      queryCondition: {},
      cacheCondition: {},
      outputUrl: ''
    }
  },
  computed: {
    condition () {
      return {
        ...this.cacheCondition,
        ...this.pageCondition
      }
    },
    otherCondition () {
      return {}
    },
    otherOutputCondition () {
      return {}
    },
    outputLink () {
      return `${this.outputUrl}?${transferToOutputCondition({
        ...this.cacheCondition,
        ...this.otherOutputCondition,
        domain: config.baseOrigin,
        SID: store.getters['user/getSID']
      })}`
    }
  },
  methods: {
    async getList (data) {
      if (data) {
        this.list = data
        return false
      }
      try {
        if (!this.service) {
          this.$message.error('未定义请求')
        }
        this.beforeGetList()
        this.loading = true
        const res = await this.service(this.condition)
        this.resData = res.data
        this.list = this.transferList(res.data.list || [])
        this.pageData = res.data.page || this.pageData
        return Promise.resolve(res)
      } catch (e) {
        // this.$message.error(e.message)
        return Promise.reject(e)
      } finally {
        this.loading = false
      }
    },
    // 列表请求前执行
    beforeGetList () {},
    transferList (list) {
      return list
    },
    handleChange (pageNo) {
      this.$set(this.pageCondition, 'pageNo', pageNo || this.pageCondition.pageNo)
      this.getList()
    },
    handlePageSizeChange (size) {
      this.$set(this.pageCondition, 'pageSize', size)
      this.handleChange(1)
    },
    handlePageOnChange (page) {
      this.handleChange(page)
    },
    search () {
      this.cacheCondition = { ...{}, ...this.queryCondition, ...this.otherCondition }
      this.handleChange(1)
    },
    onExport () {
      openWindow(this.outputLink)
    }
  },
  created () {
    this.cacheCondition = { ...{}, ...this.queryCondition, ...this.otherCondition }
  }
}
